﻿using Koala.Pro.CodeGenerator.UI.DatabaseModel.Schema;

namespace Koala.Pro.CodeGenerator.UI.Common.Adapter.SqlsugarWPF
{
    public class ViewModelAdapter : AbstractAdapter
    {
        private const string SUFFIX_LIST_CLASS = "ListViewModel";

        private const string SUFFIX_EDIT_CLASS = "EditViewModel";

        private string _tableName = string.Empty;

        private List<string> _editFields;

        private List<string> _editCheck;

        private List<string> _searchFields;

        private List<string> _searchDisplay;

        public ViewModelAdapter(DatabaseInfo databaseInfo, List<string> selectedTableNames, List<string> searchFields, List<string> searchDisplay, List<string> editFields, List<string> editCheck, string duplicateCheckField, string templateFile)
            : base(databaseInfo, selectedTableNames, templateFile)
        {
            DirectoryOfOutput = "ViewModels";
            FileExtension = ".cs";

            _tableName = selectedTableNames.FirstOrDefault();
            
            _searchFields = searchFields;
            _searchDisplay = searchDisplay;
            _editFields = editFields;
            _editCheck = editCheck;
          
            var tableInfo = databaseInfo.TableList[_tableName];
          
            if (templateFile.Contains(SUFFIX_LIST_CLASS))
            {
                FileNameOfOutput = tableInfo.Name.Alias.ToCapit() + SUFFIX_LIST_CLASS;
            }
            else
            {
                FileNameOfOutput = tableInfo.Name.Alias.ToCapit() + SUFFIX_EDIT_CLASS;
            }
           
            context.Put("DisplayColumnString", string.Join(",", _searchDisplay));

            PrepareClass(tableInfo);
            OutputFile();
        }

        private void PrepareClass(TableInfo tableInfo)
        {
            context.Put("TableInfo", tableInfo);
            context.Put("ClassName", tableInfo.Name.Alias.ToCapit());
            string primaryKeyNetType = "int";
            foreach (var item in tableInfo.ColumnList)
            {
                if (item.Value.IsPrimaryKey)
                {
                    primaryKeyNetType = item.Value.NetType.Alias.ToString();
                    break;
                }
            }
            context.Put("PrimaryKeyNetType", primaryKeyNetType);
        }
    }
}
